package com.nthink.indicators.service.hospitalindicators.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nthink.indicators.mapper.hospitalindicators.HospitalIncomeMapper;
import com.nthink.indicators.pojo.hospitalindicators.HospitalIncome;
import com.nthink.indicators.pojo.sunburst.DataModel;
import com.nthink.indicators.service.hospitalindicators.HospitalIncomeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class HospitalIncomeServiceImpl extends ServiceImpl<HospitalIncomeMapper, HospitalIncome> implements HospitalIncomeService {
    public List<DataModel> getHospitalIncome(Date startTime, Date endTime){
        List<HospitalIncome> hospitalIncomeList = baseMapper.getHospitalIncome(startTime,endTime);

        List<DataModel> dataModelList = new ArrayList<>();

        HospitalIncome lastModel = null;
        DataModel thisDataModel = null;
        double sum = 0;
        for (int i = 0; i < hospitalIncomeList.size(); i++) {
            HospitalIncome thisModel = hospitalIncomeList.get(i);
            if (lastModel == null || !thisModel.getCateID().equals(lastModel.getCateID())){

                if (thisDataModel!=null){
                    thisDataModel.setValue(sum);
                }

                thisDataModel = new DataModel();
                thisDataModel.setName(thisModel.getCateName());
                thisDataModel.setChildren(new ArrayList<> ());
                dataModelList.add(thisDataModel);


                lastModel = thisModel;
                sum = 0;
            }
            DataModel childDataModel = new DataModel();
            childDataModel.setName(thisModel.getCateItemName());
            List<DataModel> inOutList = new ArrayList();

            if (thisModel.getInAmount()>0){
                DataModel inModel = new DataModel();
                inModel.setName("住院");
                inModel.setValue(thisModel.getInAmount());
                inOutList.add(inModel);
            }

            if (thisModel.getOutAmount()>0){
                DataModel outModel = new DataModel();
                outModel.setName("门诊");
                outModel.setValue(thisModel.getOutAmount());
                inOutList.add(outModel);
            }

            childDataModel.setChildren(inOutList);
            childDataModel.setValue(thisModel.getInAmount() + thisModel.getOutAmount());

            if (childDataModel.getValue()>0){

                sum+=childDataModel.getValue();
                thisDataModel.getChildren().add(childDataModel);
            }
        }

        if (thisDataModel!=null){
            thisDataModel.setValue(sum);
        }

        return dataModelList;
    }
}
